import React, { useState } from 'react';
import AnimatedTransition from '../AnimatedTransition';
import './styleCss/Cates.scss';
import type { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
// 引入并发控制器
// import { ConcurrentRequestController } from '../axios/concurrentRequest';
// import * as XLSX from 'xlsx';
import api from '../axios/index';
import { Form, Input, Button, TextArea, ImageUploader, Toast } from 'antd-mobile';
import ExportExcelButton from '../compages/ExportExcelButton';
import ImportExcelModal from '../compages/ImportExcelModal';

const Cates = () => {
    // 创建一个最大并发数为2的控制器
    // const controller = new ConcurrentRequestController(2);
    // ... 你的其他状态和逻辑
    const [importVisible, setImportVisible] = useState(false);

    const products = [
        {
            images: '商品图片',
            title: '商品标题',
            context: '商品描述',
            price: '商品价格'
        },
    ]
    const maxCount = 3
    const [fileList, setFileList] = useState<ImageUploadItem[]>([]);

    const [formData, setFormData] = useState({
        images: '',
        title: '',
        context: '',
        price: ''
    })

    // 上传函数
    const uploadImage = async (file: File): Promise<ImageUploadItem> => {
        try {
            const formData = new FormData();
            formData.append('image', file);
            const res = await api.post('/upload-image', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            return { url: res.data.data.url };
        } catch (error) {
            // 类型守卫，判断 error 是 AxiosError 类型
            if (typeof error === 'object' && error !== null && 'response' in error) {
                // @ts-expect-error error.response 是 AxiosResponse 类型
                if (error.response && error.response.status === 403) {
                    // 不提示用户
                    console.warn('图片上传403，已静默处理');
                    return { url: '' }; // 返回空url, 防止ImageUploader报错
                }
            }

            // 其它错误正常抛出或提示
            throw error;
        }
    }

    const onFinish = async () => {
        const imageUrls = fileList.map(f => f.url);

        // 2. 组装要提交的数据
        const postData = {
            images: imageUrls, // 图片url字符串
            title: formData.title,
            context: formData.context,
            price: formData.price
        }
        try {
            const response = await api.post('/add', postData);
            console.log(response);
            if (response.data.code === 200) {
                alert('商品添加成功!');
                setFormData({
                    images: '',
                    title: '',
                    context: '',
                    price: ''
                });
                setFileList([]); // 清空图片
                window.location.reload();
            }
        } catch (error) {
            alert('提交失败：' + error)
        }
    }

    // const batchAddCates = (dataList: unknown[]) => {
    //     return Promise.all(
    //         dataList.map(data =>
    //             controller.add(() =>
    //                 api.post('/add', data) // 替换为你的单条添加接口
    //             )
    //         )
    //     )
    // }
    // 解析 Excel 文件为数据数组
    // const parseExcelFile = async (file: File): Promise<unknown[]> => {
    //     return new Promise((resolve, reject) => {
    //         const reader = new FileReader();
    //         reader.onload = (e) => {
    //             try {
    //                 const data = new Uint8Array(e.target?.result as ArrayBuffer);
    //                 const workbook = XLSX.read(data, { type: 'array' });
    //                 const firstSheetName = workbook.SheetNames[0];
    //                 const worksheet = workbook.Sheets[firstSheetName];
    //                 const jsonData = XLSX.utils.sheet_to_json(worksheet);
    //                 resolve(jsonData);
    //             } catch (err) {
    //                 reject(err);
    //             }
    //         };
    //         reader.onerror = reject;
    //         reader.readAsArrayBuffer(file);
    //     })
    // }

    // 使用axios的并发次数封装单个请求，进行批量添加商品
    // const handleBatchImport = async (file: File) => {
    //     console.log('批量导入数据：', file);
    //     const rawList = await parseExcelFile(file);
    //     console.log('解析后的数据：', rawList);
    //     const dataList = rawList.map(item => {
    //         const obj = item as Record<string, unknown>;
    //         // 取图片字段，优先 images, 其次 图片、图片url 等
    //         let images: string[] = [];
    //         if (Array.isArray(obj.images)) {
    //             images = obj.images.filter(Boolean) as string[];
    //         } else if (typeof obj.images === 'string' && obj.images) {
    //             images = [obj.images];
    //         } else if (typeof obj.图片 === 'string' && obj.图片) {
    //             images = [obj.图片];
    //         }else if (typeof obj['图片地址'] === 'string' && obj['图片地址']) {
    //             images = [obj['图片地址'] as string];
    //         }
    //         return {
    //             images,
    //             title: obj.title || obj.title,
    //             context: obj.context || obj.context,
    //             price: obj.price || obj.price
    //         }
    //     })
    //     try {
    //         const res = await batchAddCates(dataList);
    //         Toast.show('批量导入成功' + res.length + '条数据')
    //     } catch (err) {
    //         const error = err as { response?: { data?: { msg?: string } }, message?: string };
    //         Toast.show('批量导入失败: ' + (error.response?.data?.msg || error.message));
    //     }
    // };

    // 批量添加商品
    const handleBatchImport = async (importedData: File) => {
        try {
            // 1. 构造 FormData
            const formData = new FormData();
            formData.append('file', importedData);

            // 2. 获取 token
            const token = localStorage.getItem('token');

            // 3. 发送 POST 请求
            const response = await api.post('/usersxlsx/batch-upload', formData, {
                headers: {
                    "Content-Type": 'multipart/form-data',
                    'Authorization': `Bearer ${token}` //如果需要鉴权
                }
            });

            if (response.data.code === 200) {
                Toast.show('批量导入成功，共导入 ' + response.data.count + ' 条数据');
            } else {
                Toast.show('批量导入失败: ' + response.data.msg);
            }
        } catch (err) {
            const error = err as { response?: { data?: { msg?: string } }, message?: string };
            Toast.show('批量导入失败: ' + (error.response?.data?.msg || error.message));
        }
    };

    return (
        <AnimatedTransition>
            <div className="cates-container">
                <h1>添加商品</h1>
                <Form
                    onFinish={onFinish}
                    footer={
                        <Button block type='submit' color='primary' size='large'>
                            提交
                        </Button>
                    }
                >
                    <Form.Item
                        name='images'
                        label={<span>商品图片</span>}
                        rules={[
                            { required: true }
                        ]}
                    >
                        <ImageUploader
                            value={fileList}
                            onChange={newList => {
                                setFileList(newList);
                                setFormData({ ...formData, images: newList.map(f => f.url).join(',') });
                            }}
                            upload={uploadImage}
                            multiple
                            maxCount={3}
                            showUpload={fileList.length < maxCount}
                            onCountExceed={exceed => {
                                Toast.show(`最多选择 ${maxCount} 张图片，你多选了 ${exceed} 张`)
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        name='title'
                        label='商品名称'
                        rules={[
                            { required: true }
                        ]}
                    >
                        <Input
                            placeholder='请输入商品名称'
                            value={formData.title}
                            onChange={(e) => {
                                // console.log(e);
                                setFormData({ ...formData, title: e })
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        name='context'
                        label='商品描述'
                        rules={[
                            { required: true }
                        ]}
                    >
                        <TextArea
                            placeholder='请输入内容'
                            value={formData.context}
                            onChange={(e) => {
                                // console.log(e);
                                setFormData({ ...formData, context: e })
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        name='price'
                        label='商品价格'
                        rules={[
                            { required: true }
                        ]}
                    >
                        <Input
                            placeholder='请输入商品价格'
                            type="number"
                            step="0.01"
                            value={formData.price}
                            onChange={(e) => {
                                // console.log(e);
                                setFormData({ ...formData, price: e })
                            }}
                        />
                    </Form.Item>
                </Form>
                <div className='button-container'>
                    {/* 批量导出按钮 */}
                    <ExportExcelButton data={products} fileName="商品列表.xlsx">
                        批量添加
                    </ExportExcelButton>
                    {/* 批量添加按钮 */}
                    <Button color="primary" style={{ marginLeft: 8 }} onClick={() => setImportVisible(true)}>
                        批量提交
                    </Button>
                </div>
                {/* 批量导入弹窗 */}
                <ImportExcelModal
                    visible={importVisible}
                    onClose={() => setImportVisible(false)}
                    onImport={handleBatchImport}
                />
            </div>
        </AnimatedTransition>
    )
}

export default Cates;